import requests
import json
import time


class grafana_lib(object):

    def __init__(self, grafana_url, token):
        self.grafana_url = grafana_url
        self.token = token
        self.headers = {
            "Authorization" : "Bearer " + self.token,
            "Content-Type": "application/json"
        }

        self.form_headers = {
            "Authorization" : "Bearer " + self.token,
            "Content-Type": "application/x-www-form-urlencoded"    
        }

    
    def get_folders(self):
        url = self.grafana_url + '/api/folders'
        print(url)
        data = requests.get(url, headers=self.headers)
        return data.json()


    # 通过folderIds获取某个文件夹下的所有dashboard, folderIds的id从 get_folders 的请求可以获取
    def get_folder_dashboard_by_id(self, folder_id):
        url = self.grafana_url + '/api/search?folderIds=' + str(folder_id)
        print(url)
        data = requests.get(url, headers=self.headers)
        return data.json()


    # 响应包含dashboard的所有信息, 若上述dashuboard的id为59，则下面请求会获取dashboard的大致信息
    def get_dashboard_by_id(self, dashboard_id):
        url = self.grafana_url + '/api/search?dashboardIds=' + str(dashboard_id)
        print(url)


    def get_dashboard_by_uid(self, dashboard_uid):
        url = self.grafana_url + '/api/dashboards/uid/' + str(dashboard_uid)
        print(url)
        data = requests.get(url, headers=self.headers)
        return data.json()

    
    def get_datasource(self):
        url = self.grafana_url + '/api/datasources'
        print(url)
        data = requests.get(url, headers=self.headers)
        return data.json()


    def query_grafana(self, datasource_id, promql_query):
        data = {
            'query': promql_query,
            'time': time.time()
        }
        print(data)

        url = self.grafana_url + '/api/datasources/proxy/' + str(datasource_id) + '/api/v1/query'

        response = requests.post(url, headers=self.form_headers, data=data)
        # 输出查询结果
        print(json.dumps(response.json(), indent=4))

        if response.status_code == 200:
            return json.dumps(response.json(), indent=4)
        else:
            return None